package com.bankcomm.net.http;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

public class IXAsyncImageLoader {

	// 为了加快速度，在内存中开启缓存（主要应用于重复图片较多时，或者同一个图片要多次被访问，比如在ListView时来回滚动）
	private HashMap<String, SoftReference<Drawable>> imageCache;

	public IXAsyncImageLoader() {
		imageCache = new HashMap<String, SoftReference<Drawable>>();
	}

	public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) {
		// 如果缓存过就从缓存中取出数据
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Drawable> softReference = imageCache.get(imageUrl);
			Drawable drawable = softReference.get();
			if (drawable != null) {
				return drawable;
			}
		}

		// 缓存中没有图像，则从网络上取出数据，并将取出的数据缓存到内存中
		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
			}
		};
		new Thread() {
			@Override
			public void run() {
				Drawable drawable = loadImageFromUrl(imageUrl);
				imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
				Message message = handler.obtainMessage(0, drawable);
				handler.sendMessage(message);
			}
		}.start();
		return null;
	}

	// =======================================================================从网络上取数据方法 BEGIN
	public static Drawable loadImageFromUrl(String url) {
		byte[] data = getImage(url); // 得到图片的输入流
		// 二进制数据生成位图
		if (data != null) {
			Bitmap bit = BitmapFactory.decodeByteArray(data, 0, data.length);
			return new BitmapDrawable(bit);
		} else {
			return null;
		}
	}

	public static byte[] getImage(String path) {
		byte[] bytes = null;
		try {
			URL url = new URL(path); // 设置URL
			HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 打开连接
			conn.setRequestMethod("GET"); // 设置请求方法

			// 设置连接超时时间为5s
			conn.setConnectTimeout(5000);
			InputStream inputStream = conn.getInputStream(); // 取得字节输入流
			bytes = readInputStream(inputStream);
		} catch (Exception e) {
			return bytes;
		}
		return bytes; // 返回byte数组
	}

	public static byte[] readInputStream(InputStream inputStream) throws Exception {
		int len = 0;
		byte buf[] = new byte[1024];
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		while ((len = inputStream.read(buf)) != -1) {
			outputStream.write(buf, 0, len); // 把数据写入内存
		}
		// 关闭内存流
		outputStream.close();
		inputStream.close();
		return outputStream.toByteArray(); // 把内存输出流转换成byte数组
	}

	// =======================================================================从网络上取数据方法 END

	// 对外界开放的回调接口
	public interface ImageCallback {
		public void imageLoaded(Drawable imageDrawable, String imageUrl);
	}
}
